@tool
extends PanelContainer

@onready var convert_button: Button = $MarginContainer/TabContainer/ConvertBlock/HBoxContainer/ConvertButton
@onready var overwrite_box: CheckBox = $MarginContainer/TabContainer/ConvertBlock/HBoxContainer/OverwriteBox
@onready var scenes_path: TextEdit = $MarginContainer/TabContainer/ConvertBlock/ScenesPath
@onready var resources_path: TextEdit = $MarginContainer/TabContainer/ConvertBlock/ResourcesPath

const BuildingBlock = preload("res://resources/procedural_buildings/building_block.gd")

func _ready() -> void:
	convert_button.button_down.connect(on_convert_button_click)

func on_convert_button_click() -> void:
	var scenes_dir = DirAccess.open(scenes_path.text)
	var resources_dir = DirAccess.open(resources_path.text)
	
	if !scenes_dir:
		printerr('Scenes dir doesnt exist!')
		return
	
	if !resources_dir:
		printerr('Resources dir doesnt exist!')
		return
	
	convert_scenes_dir(scenes_dir, resources_dir, overwrite_box.button_pressed)


func convert_scenes_dir(
		target_dir: DirAccess, 
		result_dir: DirAccess, 
		overwrite_existing: bool = false
	):
	var target_files = target_dir.get_files()
	var target_subfolders = target_dir.get_directories()
	
	for dir in target_subfolders:
		if not result_dir.dir_exists(dir):
			result_dir.make_dir(dir)
	
	for file in target_files:
		var path = target_dir.get_current_dir() + '/' + file
		var result_path = result_dir.get_current_dir() + '/' + file.replace('.tscn', '.tres')
		var packed_scene = load(path)
		var resource = convert_scene(packed_scene)
		
		if not FileAccess.file_exists(result_path) or overwrite_existing:
			ResourceSaver.save(resource, result_path)
		
	for dir in target_subfolders:
		var target_path = target_dir.get_current_dir() + '/' + dir
		var result_path = result_dir.get_current_dir() + '/' + dir
		convert_scenes_dir(
			DirAccess.open(target_path),
			DirAccess.open(result_path),
			overwrite_existing
		)

func convert_scene(scenePack: PackedScene) -> BuildingBlock:
	var scene = scenePack.instantiate()
	var resource = BuildingBlock.new()
	resource.scene = scenePack
	var children: Dictionary[String, Array] = {'root': []}
	for child in scene.get_children():
		if child.name.begins_with('anchor_'):
			children[child.name] = []
	resource.childern = children
	return resource
